//
//  PayDelegateMoneyView.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/6.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "PayDelegateMoneyView.h"
#import <AlipaySDK/AlipaySDK.h>
#import "APAuthInfo.h"
#import "APOrderInfo.h"
#import "APRSASigner.h"
#import "AlipayCustom.h"
@interface PayDelegateMoneyView ()
@property (nonatomic, strong)UIButton * wechatBtn;
@property (nonatomic, strong)UIButton * alipayBtn;
@property (nonatomic, assign)int payWay;//1、微信支付  2、支付宝支付
@property (nonatomic, strong) UIActivityIndicatorView * activityIndicator;//菊花
- (void)weiXinpay:(NSDictionary *)dic;//微信支付
- (void)showError:(NSError*)error;
- (void)alipayWay:(NSString * )codeString;
@end

@implementation PayDelegateMoneyView(networking)
//微信支付
- (void)weChatPay{
    [self.activityIndicator startAnimating];
    NSDictionary * dic = @{
                           @"unionid":[UserModel sharedInstanced].userID,
                           };
    [self.activityIndicator startAnimating];
    [[AFAppDotNetAPIClient sharedClient] POST:@"authApi/payagent" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.activityIndicator stopAnimating];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self weiXinpay:responseObject[@"list"]];
        }else{
            [self makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self.activityIndicator stopAnimating];
    }];
}
//阿里支付
- (void)aliPay{
    [self.activityIndicator startAnimating];
    NSDictionary * dic = @{
                           @"unionid":[UserModel sharedInstanced].userID,
                           };
    [self.activityIndicator startAnimating];
    [[AFAppDotNetAPIClient sharedClient] POST:@"usApi/alipay_daili" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.activityIndicator stopAnimating];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self alipayWay:responseObject[@"list"]];
        }else{
            [self makeToast:responseObject[@"msg"] duration:1 position:CSToastPositionCenter];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self.activityIndicator stopAnimating];
    }];
}
@end

@implementation PayDelegateMoneyView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.alpha = 0;
        //标题
        UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
        titleLab.text = @"会员费支付";
        titleLab.textColor = [UIColor blackColor];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.font = DEF_FontSize_14;
        titleLab.backgroundColor = getColor(mainColor);
        [self addSubview:titleLab];
        //说明
        UILabel * contentLab = [[UILabel alloc] initWithFrame:CGRectMake(10/WIDTH_6_SCALE, titleLab.bottom + 20/WIDTH_6_SCALE, SCREEN_WIDTH - 20/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
        contentLab.font = DEF_FontSize_14;
        contentLab.textColor = [UIColor blackColor];
        contentLab.textAlignment = NSTextAlignmentCenter;
        contentLab.text = @"完成代理费支付，开启你的购物创业之旅";
//        //文字不同颜色处理
//        NSMutableAttributedString * contentTextStr = [[NSMutableAttributedString alloc] initWithString:@"完成代理费支付，开启你的\n购物创业之旅金额199元"];
//        NSRange range1 = [[contentTextStr string] rangeOfString:@"完成代理费支付，开启你的购物创业之旅"];
//        [contentTextStr addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:range1];
//        NSRange range2 = [[contentTextStr string] rangeOfString:@"金额199元"];
//        [contentTextStr addAttribute:NSForegroundColorAttributeName value:getColor(mainRedColor) range:range2];
//        contentLab.attributedText = contentTextStr;
//        contentLab.numberOfLines = 0;
//        contentLab.lineBreakMode = 0;
        [self addSubview:contentLab];
        //金额
        UILabel * moneyLab = [[UILabel alloc] initWithFrame:CGRectMake(0, contentLab.bottom, SCREEN_WIDTH, contentLab.height)];
        moneyLab.font = DEF_FontSize_14;
        moneyLab.textColor = getColor(mainRedColor);
        moneyLab.textAlignment = NSTextAlignmentCenter;
        moneyLab.text = @"金额199元";
        [self addSubview:moneyLab];
        //微信图标
        UIImageView * wechatImg = [[UIImageView alloc] initWithFrame:CGRectMake(20/WIDTH_6_SCALE, moneyLab.bottom + 20/WIDTH_6_SCALE, 30/WIDTH_6_SCALE, 28/WIDTH_6_SCALE)];
        wechatImg.image = [UIImage imageNamed:@"weChatPay"];
        [self addSubview:wechatImg];
        //微信标题
        UILabel * wechatLab = [[UILabel alloc] initWithFrame:CGRectMake(wechatImg.right + 12/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
        wechatLab.centerY = wechatImg.centerY;
        wechatLab.font = DEF_FontSize_14;
        wechatLab.textAlignment = NSTextAlignmentLeft;
        wechatLab.text = @"微信支付";
        wechatLab.textColor = [UIColor blackColor];
        [self addSubview:wechatLab];
        //微信按钮
        self.wechatBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        self.wechatBtn.centerY = wechatLab.centerY;
        self.payWay = 1;
        [self.wechatBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
        [self addSubview:self.wechatBtn];
        //微信行按钮
        UIButton * wechatCoverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, wechatImg.top, SCREEN_WIDTH, wechatImg.height)];
        [wechatCoverBtn addTarget:self action:@selector(wechatCoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [wechatCoverBtn setBackgroundColor:[UIColor clearColor]];
        [self addSubview:wechatCoverBtn];
        //支付宝图标
        UIImageView * alipayImg = [[UIImageView alloc] initWithFrame:CGRectMake(20/WIDTH_6_SCALE, 40/WIDTH_6_SCALE + wechatImg.bottom, 28/WIDTH_6_SCALE, 28/WIDTH_6_SCALE)];
        alipayImg.image = [UIImage imageNamed:@"AliPay"];
        [self addSubview:alipayImg];
        //支付宝标题
        UILabel * alipayLab = [[UILabel alloc] initWithFrame:CGRectMake(alipayImg.right + 12/WIDTH_6_SCALE, 0, 100/WIDTH_6_SCALE, 15/WIDTH_6_SCALE)];
        alipayLab.centerY = alipayImg.centerY;
        alipayLab.font = DEF_FontSize_14;
        alipayLab.text = @"支付宝支付";
        alipayLab.textColor = [UIColor blackColor];
        alipayLab.textAlignment = NSTextAlignmentLeft;
        [self addSubview:alipayLab];
        //支付宝按钮
        self.alipayBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 15/WIDTH_6_SCALE - 16/WIDTH_6_SCALE, 0, 16/WIDTH_6_SCALE, 16/WIDTH_6_SCALE)];
        self.alipayBtn.centerY = alipayLab.centerY;
        [self.alipayBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
        [self addSubview:self.alipayBtn];
        //支付宝行按钮
        UIButton * alipayCoverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, alipayImg.top, SCREEN_WIDTH, alipayImg.height)];
        [alipayCoverBtn addTarget:self action:@selector(alipayCoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [alipayCoverBtn setBackgroundColor:[UIColor clearColor]];
        [self addSubview:alipayCoverBtn];
        //上级代付
        UIButton * superiorPayBtn = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 146/WIDTH_6_SCALE)/2, self.alipayBtn.bottom + 40/WIDTH_6_SCALE, 146/WIDTH_6_SCALE, 40/WIDTH_6_SCALE)];
        [superiorPayBtn addTarget:self action:@selector(superiorPayBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [superiorPayBtn setTitle:@"请上级代付" forState:UIControlStateNormal];
        [superiorPayBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        superiorPayBtn.titleLabel.font = DEF_FontSize_12;
        superiorPayBtn.layer.cornerRadius = 4;
        superiorPayBtn.layer.masksToBounds = YES;
        superiorPayBtn.layer.borderWidth = 1;
        superiorPayBtn.layer.borderColor = getColor(@"c6c6c6").CGColor;
        superiorPayBtn.hidden = YES;
        [self addSubview:superiorPayBtn];
        //立即支付
        UIButton * payNowBtn = [[UIButton alloc] initWithFrame:CGRectMake(10/WIDTH_6_SCALE, self.height - 76/WIDTH_6_SCALE, SCREEN_WIDTH - 20/WIDTH_6_SCALE, 45/WIDTH_6_SCALE)];
        [payNowBtn addTarget:self action:@selector(payNowBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [payNowBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [payNowBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [payNowBtn setBackgroundColor:getColor(mainRedColor)];
        payNowBtn.titleLabel.font = DEF_FontSize_14;
        payNowBtn.layer.cornerRadius = 6;
        payNowBtn.layer.masksToBounds = YES;
        [self addSubview:payNowBtn];
        
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(aliPaySucceed:)
                                                     name:ZLAliReturnSucceedPayNotification
                                                   object:nil];//支付成功
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(aliPayFailed:)
                                                     name:ZLAliReturnFailedPayNotification
                                                   object:nil];//支付失败
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(weixinPaySuccess:) name:WeChatReturnSucceedPayNotification object:nil];//微信支付
        
        [self addSubview:self.activityIndicator];

    }return self;
}
- (UIActivityIndicatorView *)activityIndicator{
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleGray)];
//        [self.view addSubview:self.activityIndicator];
        //设置小菊花的frame
        _activityIndicator.frame= CGRectMake(0, 0, 100/WIDTH_6_SCALE, 100/WIDTH_6_SCALE);
        _activityIndicator.center = self.center;
        //设置小菊花颜色
        _activityIndicator.color = getColor(textGrayColor);
        //设置背景颜色
        _activityIndicator.backgroundColor = [UIColor colorWithRed:231 green:231 blue:231 alpha:1];
        //刚进入这个界面会显示控件，并且停止旋转也会显示，只是没有在转动而已，没有设置或者设置为YES的时候，刚进入页面不会显示
        _activityIndicator.hidesWhenStopped = YES;
    }return _activityIndicator;
}
- (void)showView{
    [[UIApplication sharedApplication].delegate.window addSubview:self];
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 1;
    }];
}
- (void)cancelView{
    [UIView animateWithDuration:.15 animations:^{
        self.alpha = 0 ;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}
- (void)wechatCoverBtnClick:(UIButton *)sender{
    NSLog(@"微信支付");
    self.payWay = 1;
    [self.wechatBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
    [self.alipayBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
}
- (void)alipayCoverBtnClick:(UIButton *)sender{
    NSLog(@"支付宝支付");
    self.payWay = 2;
    [self.alipayBtn setImage:[UIImage imageNamed:@"paySelect"] forState:UIControlStateNormal];
    [self.wechatBtn setImage:[UIImage imageNamed:@"payUnselect"] forState:UIControlStateNormal];
}
- (void)superiorPayBtnClick:(UIButton *)sender{
    NSLog(@"上级支付");
}
- (void)payNowBtnClick:(UIButton *)sender{
    if (self.payWay == 1) {
        NSLog(@"微信支付");
        if ([self isWXAppInstalled]) {
            [self weChatPay];
        }else{
            [self makeToast:@"请安装微信" duration:1 position:CSToastPositionCenter];
            return;
        }
    }
    if (self.payWay == 2){
        NSLog(@"支付宝支付");
        [self aliPay];
    }
    if (self.payWay == 0) {
        NSLog(@"未选择");
    }
}
#pragma mark - 支付宝支付
- (void)alipayWay:(NSString *)codeString{
//    [AlipayCustom alipaySubject:@"会员费" withListID:[self get_ONLYID] withTotalAmount:@"0.01" withH5PayBlock:^(NSDictionary * _Nonnull resultDic) {
//        NSLog(@"reslut = %@",resultDic);
//        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
//            [self makeToast:@"支付失败" duration:1 position:CSToastPositionCenter];
//        }
//        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
//            [self makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
//                if (self.paySuccessBlock) {
//                    self.paySuccessBlock();
//                }
//            }];
//        }
//    }];
    [[AlipaySDK defaultService] payOrder:codeString fromScheme:@"ShengXuntechnologyMeterMart" callback:^(NSDictionary *resultDic) {
        if ([resultDic[@"resultStatus"] isEqualToString:@"6001"]) {
            [self makeToast:@"支付失败" duration:1 position:CSToastPositionCenter];
        }
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            [self makeToast:@"支付成功!" duration:1 position:CSToastPositionCenter title:nil image:nil style:nil completion:^(BOOL didTap) {
                if (self.paySuccessBlock) {
                    self.paySuccessBlock();
                }
            }];
        }
    }];
}
//支付宝支付成功
- (void)aliPaySucceed:(NSNotification *)notify{
    NSLog(@"支付宝支付成功");
    NSLog(@"%@", [[notify object] objectForKey:@"memo"]);
    [self cancelView];
}
//支付宝支付失败
- (void)aliPayFailed:(NSNotification *)notify{
    NSLog(@"支付宝支付失败");
    NSLog(@"%@", [[notify object] objectForKey:@"memo"]);
}
//微信支付（成功之后的回调）
- (void)weixinPaySuccess:(NSNotification *)notification{
    NSLog(@"成功");
    NSDictionary * dic = notification.userInfo;
    NSString * mark = dic[@"key"];
    NSLog(@"%@", mark);
    if (self.paySuccessBlock) {
        self.paySuccessBlock();
    }
}
//调起微信支付功能
- (void)weiXinpay:(NSDictionary *)dic{
    PayReq *request = [[PayReq alloc]init];
    request.partnerId = dic[@"partnerid"];
    request.timeStamp = [dic[@"timestamp"] intValue];
    request.sign = dic[@"sign"];
    request.prepayId = dic[@"prepayid"];
    request.nonceStr = dic[@"noncestr"];
    request.package = dic[@"package"];
    [WXApi sendReq:request];
}
//是否安装微信
- (BOOL)isWXAppInstalled
{
    return [WXApi isWXAppInstalled];
}
#pragma mark - networking
/**
 *  显示错误信息
 *
 *  @param error 返回的错误信息
 */
- (void) showError:(NSError*)error{
    switch (error.code) {
        case NSURLErrorNotConnectedToInternet:
            [self makeToast:@"请检查你的网络" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorTimedOut:
            [self makeToast:@"请求超时，请查看你的网络" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorCannotConnectToHost:
            [self makeToast:@"服务器繁忙，请稍后重试" duration:1 position:CSToastPositionCenter];
            break;
        case NSURLErrorNetworkConnectionLost:
            [self makeToast:@"处理过程中网络中断，请重试" duration:1 position:CSToastPositionCenter];
            break;
        default:
            [self makeToast:@"未知错误" duration:1 position:CSToastPositionCenter];
            break;
    }
}
//生成唯一字符串，成为支付宝订单号
- (NSString*)get_ONLYID{
    CFUUIDRef uuidRef =CFUUIDCreate(NULL);
    CFStringRef uuidStringRef =CFUUIDCreateString(NULL, uuidRef);
    NSString *uniqueId = (__bridge NSString *)(uuidStringRef);
    return uniqueId;
}
@end
